﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using WPFServices.Models.AI;

namespace WPFServices.Services.AI
{
    public class ChatService
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl;

        public ChatService(string baseUrl = "http://localhost:5264/api/")
        {
            _baseUrl = baseUrl.TrimEnd('/') + "/";
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri(_baseUrl);
            _httpClient.Timeout = TimeSpan.FromMinutes(5);
        }

        /// <summary>
        /// 流式聊天 - 使用回调模式
        /// </summary>
        public async Task SendStreamChatAsync(
            AiRequestDto request,
            Action<StreamChunk> onChunkReceived,
            CancellationToken cancellationToken = default)
        {
            var json = JsonSerializer.Serialize(request, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            HttpResponseMessage response = null;
            Stream stream = null;
            StreamReader reader = null;

            try
            {
                response = await _httpClient.PostAsync("Ai/AskStream", content, cancellationToken);
                response.EnsureSuccessStatusCode();

                stream = await response.Content.ReadAsStreamAsync();
                reader = new StreamReader(stream, Encoding.UTF8);

                string line;
                while ((line = await reader.ReadLineAsync()) != null && !cancellationToken.IsCancellationRequested)
                {
                    if (string.IsNullOrWhiteSpace(line)) continue;

                    if (line.StartsWith("data: "))
                    {
                        var jsonData = line.Substring(6).Trim();

                        if (jsonData == "[DONE]")
                        {
                            onChunkReceived(new StreamChunk
                            {
                                Type = "Done",
                                Content = "",
                                Timestamp = DateTime.Now
                            });
                            break;
                        }

                        var chunk = TryParseStreamChunk(jsonData);
                        if (chunk != null)
                        {
                            onChunkReceived(chunk);
                            // 添加小延迟确保UI能及时更新
                            await Task.Delay(50, cancellationToken);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                onChunkReceived(new StreamChunk
                {
                    Type = "Error",
                    Content = $"请求失败: {ex.Message}",
                    Timestamp = DateTime.Now
                });
            }
            finally
            {
                reader?.Dispose();
                stream?.Dispose();
                response?.Dispose();
            }
        }

        /// <summary>
        /// 尝试解析流式数据块
        /// </summary>
        private StreamChunk TryParseStreamChunk(string jsonData)
        {
            try
            {
                var chunk = JsonSerializer.Deserialize<StreamChunk>(jsonData, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });
                return chunk;
            }
            catch (JsonException ex)
            {
                return new StreamChunk
                {
                    Type = "Error",
                    Content = $"JSON解析错误: {ex.Message}",
                    Timestamp = DateTime.Now
                };
            }
            catch (Exception ex)
            {
                return new StreamChunk
                {
                    Type = "Error",
                    Content = $"数据解析失败: {ex.Message}",
                    Timestamp = DateTime.Now
                };
            }
        }

        /// <summary>
        /// 回调模式聊天 - 等待完整响应
        /// </summary>
        public async Task<CallbackResponse> SendCallbackChatAsync(
            AiRequestDto request,
            CancellationToken cancellationToken = default)
        {
            var json = JsonSerializer.Serialize(request, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                using var response = await _httpClient.PostAsync("Ai/AskCallback", content, cancellationToken);
                response.EnsureSuccessStatusCode();

                var responseJson = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<CallbackResponse>(responseJson, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                return result ?? new CallbackResponse { Success = false, Error = "响应解析失败" };
            }
            catch (HttpRequestException ex)
            {
                return new CallbackResponse
                {
                    Success = false,
                    Error = $"网络请求失败: {ex.Message}"
                };
            }
            catch (TaskCanceledException)
            {
                return new CallbackResponse
                {
                    Success = false,
                    Error = "请求已取消"
                };
            }
            catch (Exception ex)
            {
                return new CallbackResponse
                {
                    Success = false,
                    Error = $"未知错误: {ex.Message}"
                };
            }
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}